import matplotlib.pyplot as plt
import time

import datetime as dt
import easyquotation


import json,requests,datetime;    


import pandas as pd  #
import random

import numpy as np


import datetime
import backtrader as bt
import backtrader.feeds as btfeeds
# Create a subclass of SignaStrategy to define the indicators and signals


import backtrader.feeds as btfeeds
import tushare as ts
# 取得Data Feed对象
def get_tushare_online_daily_data():
    """将A股票日线数据返回BT Data
    """
    # 参数部分
    stock_id = "603260.SH"
    start = "20200101"
    end = "20220910"
    dt_start = datetime.datetime.strptime(start, "%Y%m%d")
    dt_end = datetime.datetime.strptime(end, "%Y%m%d")
    TOKEN = 'abcd1234'
    ts.set_token('a6cfea28f42aefefa105175932bf6af4196ad6100d8bb94842df5383')
    pro = ts.pro_api()
    try:
        # 加载数据
        df = pro.daily(ts_code=stock_id, start_date=start, end_date='end')
        df.sort_values(by=["trade_date"], ascending=True,
                       inplace=True)    # 按日期先后排序
        df.reset_index(inplace=True, drop=True)
        df.sort_values(by=["trade_date"], ascending=True, inplace=True)
        # 将日期列，设置成index
        df.index = pd.to_datetime(df.trade_date, format='%Y%m%d')
        # 增加一列openinterest
        df['openinterest'] = 0.00
        # 取出特定的列
        df = df[['open', 'high', 'low', 'close', 'vol', 'openinterest']]
        # 列名修改成指定的
        df.rename(columns={"vol": "volume"}, inplace=True)
        data = bt.feeds.PandasData(dataname=df, fromdate=dt_start, todate=dt_end)
        return data
    except Exception as err:
        print("下载{0}完毕失败！")
        print("失败原因 = " + str(err))




class SmaCross(bt.SignalStrategy):
    # list of parameters which are configurable for the strategy
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30   # period for the slow moving average
    )

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
        self.signal_add(bt.SIGNAL_LONG, crossover)  # use it as LONG signal


cerebro = bt.Cerebro()  # create a "Cerebro" engine instance

# Create a data feed
data = get_tushare_online_daily_data()
cerebro.adddata(data)  # Add the data feed

cerebro.addstrategy(SmaCross)  # Add the trading strategy
cerebro.run()  # run it all
cerebro.plot()  # and plot it with a single command